import React, { useState, useEffect } from 'react'
import { Table, Tree, Tag, Button, Modal, Popover, Switch } from 'antd'
const { confirm } = Modal
import axios from 'axios'
import { SearchOutlined, DeleteOutlined, ExclamationCircleFilled, EditOutlined } from '@ant-design/icons'
export default function RoleList() {
  const [dataSource, setDataSource] = useState<any[]>([])
  const [rightList, setRightList] = useState([])
  const [currentRight, setCurrentRight] = useState([])
  const [currentId, setCurrentId] = useState(0)
  useEffect(() => {
    axios.get(`/roles`).then((res) => {
      console.log(res.data)
      setDataSource(res.data)
    })
    axios.get(`/rights?_embed=children`).then((res) => {
      setRightList(res.data)
    })
  }, [])
  const [isModalOpen, setIsModalOpen] = useState(false)

  const showModal = (item: any) => {
    setIsModalOpen(true)
    setCurrentRight(item.rights)
    setCurrentId(item.id)
  }

  const handleOk = () => {
    setIsModalOpen(false)
    console.log(currentRight)
    setDataSource(
      dataSource.map((item: any) => {
        if (item.id === currentId) {
          return {
            ...item,
            rights: currentRight
          }
        }
        return item
      })
    )
    axios.patch(`/roles/${currentId}`, {
      rights: currentRight
    })
  }

  const handleCancel = () => {
    setIsModalOpen(false)
  }
  const onCheck = (checkkeys: any) => {
    console.log(checkkeys)
    setCurrentRight(checkkeys.checked)
  }
  //删除
  const delMethods = (item: any) => {
    setDataSource(dataSource.filter((item2: any) => item2.id !== item.id))
    axios.delete(`/roles/${item.id}`)
  }
  const showConfirm = (item: any) => {
    confirm({
      title: '您确定要删除?',
      icon: <ExclamationCircleFilled />,
      content: 'Some descriptions',
      onOk() {
        delMethods(item)
      },
      onCancel() {
        console.log('Cancel')
      }
    })
  }
  const columns = [
    {
      title: 'ID',
      dataIndex: 'id',
      render: (id: string) => <b>{id}</b>
    },
    {
      title: '角色名称',
      dataIndex: 'roleName'
    },
    {
      title: '操作',
      render: (item: any) => (
        <div>
          <Button danger shape="circle" icon={<DeleteOutlined />} onClick={() => showConfirm(item)}></Button>

          <Button type="primary" shape="circle" icon={<EditOutlined />} onClick={() => showModal(item)}></Button>
        </div>
      )
    }
  ]
  return (
    <div>
      <Table dataSource={dataSource} columns={columns} rowKey="id" pagination={{ pageSize: 5 }} />
      <Modal title="Basic Modal" open={isModalOpen} onOk={handleOk} onCancel={handleCancel}>
        {/* onSelect={onSelect} */}

        <Tree onCheck={onCheck} checkable checkedKeys={currentRight} checkStrictly treeData={rightList} />
      </Modal>
    </div>
  )
}
